<template>
  <div class="grades-page">
    <el-tabs v-model="mainTab">
      <el-tab-pane label="成绩管理" name="grades">
        <el-card>
          <el-form :inline="true" :model="scoreQuery"
            class="search-form-container mb-6 bg-gray-50 p-4 rounded-lg shadow-sm">
            <div class="search-inputs-actions">
              <div class="flex items-center flex-wrap gap-x-4 gap-y-2">
                <el-form-item label="" class="mb-0">
                  <el-input v-model="scoreQuery.studentId" placeholder="学号" style="width: 150px;" clearable />
                </el-form-item>
                <el-form-item label="" class="mb-0">
                  <el-input v-model="scoreQuery.courseId" placeholder="课程编号" style="width: 150px;" clearable />
                </el-form-item>
                <el-form-item label="" class="mb-0">
                  <el-input v-model="scoreQuery.examId" placeholder="考试编号" style="width: 150px;" clearable />
                </el-form-item>
                <el-form-item class="mb-0">
                  <el-button @click="handleSearch" class="gradient-purple-blue-button">查询</el-button>
                  <el-button @click="resetScoreQuery" class="gradient-blue-cyan-button"
                    style="margin-left: 8px;">重置</el-button>
                </el-form-item>
              </div>
              <div class="flex items-center gap-x-4">
                <el-button @click="openAddDialog" class="gradient-blue-toggle-button">新增成绩</el-button>
                <el-button @click="exportScores" class="gradient-blue-toggle-button">导出成绩</el-button>
                <el-button @click="toggleView" class="gradient-blue-toggle-button">
                  {{ isCardView ? '切换为列表' : '切换为卡片' }}
                </el-button>
              </div>
            </div>
          </el-form>

          <el-row :gutter="20" class="chart-section">
            <el-col :span="8">
              <el-card>
                <h3>成绩等级分布</h3>
                <div ref="gradeDistributionChart" style="width: 100%; height: 300px;"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card>
                <h3>各课程平均分</h3>
                <div ref="courseAverageChart" style="width: 100%; height: 300px;"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card>
                <h3>学生成绩趋势 (按学号筛选)</h3>
                <div ref="studentScoreTrendChart" style="width: 100%; height: 300px;"></div>
                <p v-if="!scoreQuery.studentId" class="chart-placeholder">
                  请在上方筛选条件中输入学号以查看其成绩趋势。
                </p>
              </el-card>
            </el-col>
          </el-row>

          <div v-loading="scoreLoading" style="margin-top: 20px;">
            <template v-if="isCardView">
              <el-row :gutter="20" class="grade-card-grid">
                <template v-if="paginatedScoreList.length > 0">
                  <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in paginatedScoreList" :key="item.id">
                    <el-card class="grade-card">
                      <div class="grade-card-content">
                        <h4 class="grade-card-title">学号: {{ item.studentId }}</h4>
                        <p class="grade-card-info"><span class="info-label">课程编号:</span> {{ item.courseId }}</p>
                        <p class="grade-card-info"><span class="info-label">考试编号:</span> {{ item.examId }}</p>
                        <p class="grade-card-info"><span class="info-label">总分:</span> <span
                            style="font-weight:bold; color: #409EFF;">{{ item.totalScore }}</span></p>
                        <p class="grade-card-info"><span class="info-label">等级:</span> <span
                            style="font-weight:bold; color: #67C23A;">{{ item.grade }}</span></p>
                      </div>
                      <div class="grade-card-actions">
                        <el-button size="mini" @click="editScore(item)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="deleteScore(item.id)"
                          class="light-red-button">删除</el-button>
                      </div>
                    </el-card>
                  </el-col>
                </template>
                <div v-else class="empty-data">
                  <el-empty description="暂无成绩数据，请新增或调整搜索条件"></el-empty>
                </div>
              </el-row>
            </template>
            <template v-else>
               <el-table :data="paginatedScoreList" border style="width: 100%;">
                <el-table-column prop="id" label="ID" width="60" />
                <el-table-column prop="studentId" label="学号" width="100" />
                <el-table-column prop="courseId" label="课程编号" width="100" />
                <el-table-column prop="examId" label="考试编号" width="100" />
                <el-table-column prop="totalScore" label="总分" width="80" />
                <el-table-column prop="grade" label="等级" width="80" />
                <el-table-column label="操作" width="180">
                  <template #default="scope">
                    <el-button size="mini" @click="editScore(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="deleteScore(scope.row.id)" class="light-red-button">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
            <el-pagination class="mt-4" layout="prev, pager, next" :total="filteredScoreList.length"
              :page-size="pageSize" v-model:current-page="currentPage" @current-change="handlePageChange"
              style="justify-content: center;" />
          </div>
        </el-card>
        <el-dialog v-model="showAddDialog" :title="editMode ? '编辑成绩' : '添加成绩'" width="400px">
          <el-form :model="addForm" label-width="80px" ref="addFormRef">
            <el-form-item label="学号" prop="studentId" required>
              <el-input v-model.number="addForm.studentId" placeholder="学号" />
            </el-form-item>
            <el-form-item label="课程编号" prop="courseId" required>
              <el-input v-model.number="addForm.courseId" placeholder="课程编号" />
            </el-form-item>
            <el-form-item label="考试编号" prop="examId" required>
              <el-input v-model.number="addForm.examId" placeholder="考试编号" />
            </el-form-item>
            <el-form-item label="总分" prop="totalScore" required>
              <el-input-number v-model.number="addForm.totalScore" :min="0" :max="100" placeholder="总分" />
            </el-form-item>
            <el-form-item label="等级" prop="grade" required>
              <el-input v-model="addForm.grade" placeholder="等级" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showAddDialog = false">取消</el-button>
            <el-button type="primary" @click="submitAdd">提交</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane label="学习行为评估" name="analysis">
        <el-card>
          <el-form :inline="true" :model="query"
            class="search-form-container mb-6 bg-gray-50 p-4 rounded-lg shadow-sm">
            <div class="search-inputs-actions">
              <div class="flex items-center flex-wrap gap-x-4 gap-y-2">
                <el-form-item label="" class="mb-0">
                  <el-input v-model="query.studentId" placeholder="请输入学号" style="width: 180px" clearable />
                </el-form-item>
                <el-form-item label="" class="mb-0">
                  <el-input v-model="query.courseId" placeholder="请输入课程编号" style="width: 180px" clearable />
                </el-form-item>
              </div>
              <div class="flex items-center gap-x-4">
                <el-button @click="fetchAssessment" class="gradient-purple-blue-button">查询评估</el-button>
                <el-button @click="clearAssessment" class="gradient-blue-cyan-button">清空</el-button>
              </div>
            </div>
          </el-form>

          <el-card v-loading="assessmentLoading">
            <template v-if="effect.message">
              <el-empty :description="effect.message" />
            </template>
            <template v-else>
              <el-descriptions title="学习效果评估报告" :column="2" border>
                <el-descriptions-item label="总分" label-align="center" align="center">{{ effect.score }}</el-descriptions-item>
                <el-descriptions-item label="等级" label-align="center" align="center">{{ effect.grade }}</el-descriptions-item>
                <el-descriptions-item label="最近学习时长" label-align="center" align="center">{{ effect.studyTime }}</el-descriptions-item>
                <el-descriptions-item label="最近访问频率" label-align="center" align="center">{{ effect.accessFrequency }}</el-descriptions-item>
                <el-descriptions-item label="最近参与率" label-align="center" align="center" :span="2">{{ effect.participationRate }}</el-descriptions-item>
                <el-descriptions-item label="综合评语" label-align="center" align="center" :span="2">
                  <div style="min-height: 60px;">{{ effect.evaluation }}</div>
                </el-descriptions-item>
              </el-descriptions>
            </template>
          </el-card>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed, nextTick } from 'vue';
import gradeService from '@/services/gradeService';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';

// --- 全局状态 ---
const mainTab = ref('grades');

// --- 成绩管理 Tab 相关状态 ---
const isCardView = ref(true);
const scoreList = ref([]);
const filteredScoreList = ref([]);
const scoreLoading = ref(false);
const scoreQuery = reactive({ studentId: '', courseId: '', examId: '' });
const showAddDialog = ref(false);
const addForm = reactive({ id: null, studentId: '', courseId: '', examId: '', totalScore: '', grade: '' });
const addFormRef = ref();
const editMode = ref(false);
const currentPage = ref(1);
const pageSize = 8;
const paginatedScoreList = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return filteredScoreList.value.slice(start, end);
});
const gradeDistributionChart = ref(null);
const courseAverageChart = ref(null);
const studentScoreTrendChart = ref(null);
let myGradeDistributionChart = null;
let myCourseAverageChart = null;
let myStudentScoreTrendChart = null;


// --- 学习行为评估 Tab 相关状态 ---
const query = reactive({ studentId: '', courseId: '' });
const effect = reactive({ message: '请输入学号和课程编号进行查询。' }); // 更新初始提示信息
const assessmentLoading = ref(false);


// --- 成绩管理 Tab 相关方法 ---
const toggleView = () => { isCardView.value = !isCardView.value; };
function handleSearch() { applySearchFilters(); }
async function fetchScores() { 
  scoreLoading.value = true;
  try {
    const res = await gradeService.getAllScores();
    if (res.status === 0) {
      scoreList.value = res.data || [];
      applySearchFilters();
    } else {
      scoreList.value = [];
      ElMessage.error(res.message || '获取失败');
    }
  } finally {
    scoreLoading.value = false;
  }
}
function applySearchFilters() { 
  let tempFiltered = scoreList.value;
  if (scoreQuery.studentId) tempFiltered = tempFiltered.filter(s => String(s.studentId).includes(String(scoreQuery.studentId)));
  if (scoreQuery.courseId) tempFiltered = tempFiltered.filter(s => String(s.courseId).includes(String(scoreQuery.courseId)));
  if (scoreQuery.examId) tempFiltered = tempFiltered.filter(s => String(s.examId).includes(String(scoreQuery.examId)));
  filteredScoreList.value = tempFiltered;
  currentPage.value = 1;
}
function resetScoreQuery() { 
  Object.assign(scoreQuery, { studentId: '', courseId: '', examId: '' });
  applySearchFilters();
}
function openAddDialog() { 
  editMode.value = false;
  Object.assign(addForm, { id: null, studentId: '', courseId: '', examId: '', totalScore: '', grade: '' });
  showAddDialog.value = true;
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
}
function editScore(row) { 
  editMode.value = true;
  Object.assign(addForm, row);
  showAddDialog.value = true;
}
async function submitAdd() { 
  if (!addForm.studentId || !addForm.courseId || !addForm.examId || addForm.totalScore === '' || !addForm.grade) {
    ElMessage.error('所有字段均为必填项');
    return;
  }
  let res;
  if (editMode.value) {
    res = await gradeService.updateScore({ ...addForm });
  } else {
    res = await gradeService.addScore({ ...addForm });
  }
  if (res.status === 0) {
    ElMessage.success(editMode.value ? '编辑成功' : '添加成功');
    showAddDialog.value = false;
    editMode.value = false;
    fetchScores();
  } else {
    ElMessage.error(res.message || '操作失败');
  }
}
async function deleteScore(id) { 
  ElMessageBox.confirm('确定要删除该成绩吗？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await gradeService.deleteScore(id);
      if (res.status === 0) {
        ElMessage.success('删除成功');
        fetchScores();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    })
    .catch(() => { });
}
async function exportScores() { 
  try {
    const res = await gradeService.exportScores();
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'scores.xlsx';
    link.click();
    window.URL.revokeObjectURL(url);
    ElMessage.success('成绩表导出成功');
  } catch (error) {
    ElMessage.error('导出失败: ' + (error.message || '未知错误'));
  }
}
function handlePageChange(val) { currentPage.value = val; }
function calculateChartData() { 
  const gradeCounts = {};
  const courseScores = {};
  const studentScores = {};

  filteredScoreList.value.forEach(item => {
    gradeCounts[item.grade] = (gradeCounts[item.grade] || 0) + 1;

    if (!courseScores[item.courseId]) {
      courseScores[item.courseId] = { sum: 0, count: 0 };
    }
    courseScores[item.courseId].sum += item.totalScore;
    courseScores[item.courseId].count++;

    if (scoreQuery.studentId && String(item.studentId) === String(scoreQuery.studentId)) {
      if (!studentScores[item.studentId]) {
        studentScores[item.studentId] = [];
      }
      studentScores[item.studentId].push({ examId: item.examId, totalScore: item.totalScore, courseId: item.courseId });
    }
  });

  const gradeDistributionData = Object.entries(gradeCounts).map(([name, value]) => ({ name, value }));

  const courseAverageData = Object.entries(courseScores).map(([courseId, data]) => ({
    courseId: courseId,
    averageScore: (data.sum / data.count).toFixed(2)
  }));

  const studentTrendData = scoreQuery.studentId ? (studentScores[scoreQuery.studentId] || []) : [];
  studentTrendData.sort((a, b) => a.examId - b.examId);

  return { gradeDistributionData, courseAverageData, studentTrendData };
}
function renderCharts(gradeData, courseAvgData, studentTrendData) { 
  if (myGradeDistributionChart) myGradeDistributionChart.dispose();
  if (myCourseAverageChart) myCourseAverageChart.dispose();
  if (myStudentScoreTrendChart) myStudentScoreTrendChart.dispose();

  nextTick(() => {
    if (gradeDistributionChart.value) {
      myGradeDistributionChart = echarts.init(gradeDistributionChart.value);
      myGradeDistributionChart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        xAxis: { type: 'category', data: gradeData.map(item => item.name) },
        yAxis: { type: 'value', name: '数量' },
        series: [{ name: '成绩等级', type: 'bar', data: gradeData.map(item => item.value) }]
      });
    }

    if (courseAverageChart.value) {
      myCourseAverageChart = echarts.init(courseAverageChart.value);
      myCourseAverageChart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        // 更新图表标签
        xAxis: { type: 'category', data: courseAvgData.map(item => `课程编号: ${item.courseId}`), axisLabel: { interval: 0, rotate: 30 } },
        yAxis: { type: 'value', name: '平均分' },
        grid: { bottom: '20%' },
        series: [{ name: '平均分', type: 'bar', data: courseAvgData.map(item => item.averageScore) }]
      });
    }

    if (studentScoreTrendChart.value) {
      myStudentScoreTrendChart = echarts.init(studentScoreTrendChart.value);
      if (studentTrendData.length > 0) {
        myStudentScoreTrendChart.setOption({
          tooltip: { trigger: 'axis' },
          // 更新图表标签
          xAxis: { type: 'category', data: studentTrendData.map(item => `考试编号: ${item.examId}`), axisLabel: { interval: 0, rotate: 30 } },
          yAxis: { type: 'value', name: '总分' },
          grid: { bottom: '20%' },
          series: [{ name: '总分', type: 'line', data: studentTrendData.map(item => item.totalScore), smooth: true }]
        });
      } else {
        myStudentScoreTrendChart.clear();
      }
    }
  });
}
function updateChartsAndData() { 
  const { gradeDistributionData, courseAverageData, studentTrendData } = calculateChartData();
  renderCharts(gradeDistributionData, courseAverageData, studentTrendData);
}

// --- 学习行为评估 Tab 相关方法 ---
async function fetchAssessment() {
  if (!query.studentId || !query.courseId) {
    // 更新提示信息
    ElMessage.warning('请输入学号和课程编号才能查询');
    return;
  }

  assessmentLoading.value = true;
  Object.keys(effect).forEach(key => delete effect[key]);

  try {
    const res = await gradeService.fetchEffect({ studentId: query.studentId, courseId: query.courseId });
    Object.assign(effect, res);
  } catch (error) {
    ElMessage.error('查询评估数据失败');
    effect.message = '查询失败，请检查网络或联系管理员。';
  } finally {
    assessmentLoading.value = false;
  }
}

function clearAssessment() {
  query.studentId = '';
  query.courseId = '';
  Object.keys(effect).forEach(key => delete effect[key]);
  // 更新重置后的提示信息
  effect.message = '请输入学号和课程编号进行查询。';
}

// --- Watchers & Lifecycle Hooks ---
watch(filteredScoreList, updateChartsAndData, { deep: true });
watch(() => scoreQuery.studentId, updateChartsAndData);
watch(mainTab, (newTab) => {
  if (newTab === 'grades' && scoreList.value.length === 0) {
    fetchScores();
  }
});

onMounted(async () => {
  await fetchScores();
  window.addEventListener('resize', () => {
    myGradeDistributionChart?.resize();
    myCourseAverageChart?.resize();
    myStudentScoreTrendChart?.resize();
  });
});
</script>

<style scoped>
/* --- General Page & Layout Styles --- */
.grades-page {
  padding: 32px 24px;
  background: #f8f9fb;
}

.mb-6 { margin-bottom: 1.5rem; }
.mt-4 { margin-top: 1.5rem; }
.flex { display: flex; }
.justify-between { justify-content: space-between; }
.items-center { align-items: center; }
.flex-wrap { flex-wrap: wrap; }
.gap-x-4 { column-gap: 1rem; }
.gap-y-2 { row-gap: 0.5rem; }

.search-inputs-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  gap: 10px;
}

.search-form-container {
  background-color: #f9fafb;
  padding: 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.el-form-item.mb-0 {
  margin-bottom: 0 !important;
}

.chart-section {
  margin-top: 20px;
}
.chart-section h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #333;
}
.chart-placeholder {
  color: #909399;
  text-align: center;
  margin-top: 10px;
}


/* --- Custom Button Styles (Gradient and Lighter) --- */
.gradient-purple-blue-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #8b5dbd, #548ee0) !important;
  border-color: #8b5dbd !important;
  transition: all 0.3s ease;
}
.gradient-purple-blue-button:hover,
.gradient-purple-blue-button:focus {
  background-image: linear-gradient(to right, #9d70d1, #69a7f3) !important;
  border-color: #9d70d1 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.gradient-blue-cyan-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #548ee0, #38afb5) !important;
  border-color: #548ee0 !important;
  transition: all 0.3s ease;
}
.gradient-blue-cyan-button:hover,
.gradient-blue-cyan-button:focus {
  background-image: linear-gradient(to right, #69a7f3, #4fd3d8) !important;
  border-color: #69a7f3 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.gradient-blue-toggle-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #3f51b5, #2196f3) !important;
  border-color: #3f51b5 !important;
  transition: all 0.3s ease;
}
.gradient-blue-toggle-button:hover,
.gradient-blue-toggle-button:focus {
  background-image: linear-gradient(to right, #5c6bc0, #42a5f5) !important;
  border-color: #5c6bc0 !important;
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.light-red-button {
  background-color: #FEE2E2 !important;
  color: #EF4444 !important;
  border-color: #FEE2E2 !important;
}
.light-red-button:hover,
.light-red-button:focus {
  background-color: #FECDCD !important;
  border-color: #FECDCD !important;
}


/* --- Grade Card View Styles --- */
.grade-card-grid {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  padding-bottom: 20px;
}
.grade-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #ffffff;
  border: 1px solid #e9e9e9;
}
.grade-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.grade-card-content {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.grade-card-title {
  font-size: 1.1em;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}
.grade-card-info {
  font-size: 0.9em;
  color: #666;
  margin: 0;
  line-height: 1.4;
}
.grade-card-info .info-label {
  font-weight: 500;
  color: #444;
  margin-right: 5px;
}
.grade-card-actions {
  padding: 10px 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  background-color: #fafafa;
}
.grade-card-actions .el-button {
  min-width: unset;
  padding: 7px 12px;
  font-size: 0.85em;
}
.empty-data {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
</style>